package math;

public class Ray extends Line
{
	public Ray(Vector2D s, Vector2D e)
	{
		super(s, e);
	}
	
	public Ray(Vector2D start, double angle)
	{
		Vector2D ray = new Vector2D(1,1);
		ray.setAngle(angle);
		setStart(start);
		setEnd(new Vector2D(start.getX() + ray.getX(), start.getY() + ray.getY()));
	}
	
	public Vector2D intersection(LineSegment ls)
	{
		Vector2D intersection = super.intersection(ls);
		if(intersection == null)
			return null;
		//make sure the intersection is on the line segment
		if(Math.round(intersection.getX()) > Math.round(Math.max(ls.getStart().getX()+1, ls.getEnd().getX()+1)) ||
				Math.round(intersection.getX()) < Math.round(Math.min(ls.getStart().getX()-1, ls.getEnd().getX()-1)))
			return null;
		if(Math.round(intersection.getY()) > Math.round(Math.max(ls.getStart().getY()+1, ls.getEnd().getY()+1)) ||
				Math.round(intersection.getY()) < Math.round(Math.min(ls.getStart().getY()-1, ls.getEnd().getY()-1)))
				return null;
		//if the intersection is on the other side of the ray, no intersection
		boolean xIsPos = getStart().getX() - getEnd().getX() >= 0;
		boolean yIsPos = getStart().getY() - getEnd().getY() >= 0;
		
		if(xIsPos != (getStart().getX() - intersection.getX() >= 0) ||
			yIsPos != (getStart().getY() - intersection.getY() >= 0))
			return null;
		return intersection;
		
	}

}
